<template>
  <!-- class="absolute top-40px right-1 max-w-300px" -->
  <n-card
    v-if="visible"
    content-style="padding: 5px 10px;"
    class="absolute max-w-300px"
    :style="{ top: top + 'px', left: left + 'px' }"
  >
    <div ref="panelRef">
      <n-collapse accordion default-expanded-names="frange">
        <template #arrow="{ collapsed }">
          <n-icon v-if="collapsed">
            <PlanetOutline />
          </n-icon>
          <n-icon v-else>
            <SunnyOutline />
          </n-icon>
        </template>

        <n-collapse-item title="法兰信息" name="frange">
          <div class="max-h-full overflow-y-auto">
            <n-descriptions
              label-placement="left"
              bordered
              size="small"
              :column="1"
            >
              <template #header>
                <p class="py-2">{{ info.GroupName }}</p>
              </template>
              <n-descriptions-item
                v-for="(it, i) in info.Parameters"
                :key="i + it.name"
                :label="it.name"
              >
                {{ it.value }}
              </n-descriptions-item>
            </n-descriptions>
          </div>
        </n-collapse-item>
      </n-collapse>
    </div>
  </n-card>
</template>

<script setup>
// import { PlanetOutline, SunnyOutline } from "@vicons/ionicons5";
import { ref, onBeforeUnmount, onMounted, nextTick } from "vue";
import { useAddSignal, useRemoveSignal } from "@/hooks/useSignal";
import * as THREE from "three";

const visible = ref(false);
const info = ref({
  GroupName: "C-101/A-进料隔断阀BV-101/A前法兰",
  Parameters: [
    { name: "法兰规格", value: "DN300" },
    { name: "压力等级", value: "Class600" },
    { name: "垫片名称", value: "非金属垫片" },
    { name: "垫片规格", value: "R57" },
    { name: "螺栓规格", value: "M33×3" },
    { name: "推荐载荷", value: "100KN" },
    { name: "法兰位置", value: "--" },
  ],
});

const left = ref(40);
const top = ref(10);

const panelRef = ref(null);

const MARGIN = 20;

const positionInfoPanel = async (model) => {
  // 获取模型世界坐标
  const worldPosition = new THREE.Vector3();
  model.getWorldPosition(worldPosition);

  // 转换为屏幕坐标
  worldPosition.project(window.viewer.camera);

  // 转换为CSS像素坐标
  let x = (worldPosition.x * 0.5 + 0.5) * window.innerWidth;
  let y = (-(worldPosition.y * 0.5) + 0.5) * window.innerHeight;

  // 初始位置
  left.value = x + MARGIN;
  top.value = y;
  await nextTick();
  setTimeout(() => {
    // positionInfoPanel(object);
    // 边界检查
    if (!panelRef.value) return;
    // 这里 panelRef.value 是 DOM 元素
    const panelRect = panelRef.value.getBoundingClientRect();
    console.log(panelRect);

    // 右边界
    if (panelRect.right > window.innerWidth) {
      left.value = window.innerWidth - panelRect.width - MARGIN;
    }
    // 左边界
    if (panelRect.left < 0) {
      left.value = MARGIN;
    }
    // 下边界
    if (panelRect.bottom > window.innerHeight) {
      top.value = window.innerHeight - panelRect.height - MARGIN;
    }
    // 上边界
    if (panelRect.top < 0) {
      top.value = MARGIN;
    }
  }, 0);
};

async function objectSelected(object) {
  if (!object) {
    visible.value = false;
    return;
  }
  if (!object.userData.frangeId) {
    visible.value = false;
  } else {
    //根据frangeId获取法兰信息
    const frangeArr = [
      {
        GroupName: "C-101/A-进料隔断阀BV-101/A前法兰",
        Parameters: [
          { name: "法兰规格", value: "DN300" },
          { name: "压力等级", value: "Class600" },
          { name: "垫片名称", value: "非金属垫片" },
          { name: "垫片规格", value: "R57" },
          { name: "螺栓规格", value: "M33×3" },
          { name: "推荐载荷", value: "100KN" },
          { name: "法兰位置", value: "--" },
        ],
      },
      {
        GroupName: "C-502/A-出料隔断阀BV-502/A后法兰",
        Parameters: [
          { name: "法兰规格", value: "DN280" },
          { name: "压力等级", value: "Class800" },
          { name: "垫片名称", value: "非金属垫片" },
          { name: "垫片规格", value: "R63" },
          { name: "螺栓规格", value: "M35×3" },
          { name: "推荐载荷", value: "200KN" },
          { name: "法兰位置", value: "位置一" },
        ],
      },
    ];

    // 随机将frangeArr中的一个赋值给info
    info.value = frangeArr[Math.floor(Math.random() * frangeArr.length)];

    visible.value = true;
    await nextTick();
    positionInfoPanel(object);
  }
}

onMounted(async () => {
  useAddSignal("objectSelected", objectSelected);
  console.log("123456");
  await nextTick();
  //监听视窗变化（节流）
  let timer = null;
  const resizeObserver = new ResizeObserver(() => {
    if (timer) return;
    timer = setTimeout(() => {
      // console.log("resize");
      // console.log(window.editor.selected);
      // if (panelRef.value && window.editor.selected) {
      //   positionInfoPanel(window.editor.selected);
      // }
      visible.value = false;
      timer = null;
    }, 16);
  });
  resizeObserver.observe(window.viewer.renderer.domElement);
});

onBeforeUnmount(() => {
  useRemoveSignal("objectSelected", objectSelected);
});
</script>
